﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Bee.Util;
using Bee.Web;
using Bee.Data;
using System.Data;
using Bee.Models;
using Bee.Security.Controllers;
using Bee.BLL;

namespace Bee.Security.Controllers
{
    public class OrganizationController : AuthGroupController
    {
        static OrganizationController()
        {
            DataMapping.Instance.Register("OrganizationMapping", () =>
            {
                using (DbSession dbSession = new DbSession(ConfigUtil.GetAppSettingValue<string>(Constants.AuthDbConnectionKey)))
                {
                    DataTable data = dbSession.ExecuteCommand(@"select a.*, b.orgcode, b.address, b.remark, b.owneremployeeid
                    from authgroup a inner join organization b on a.id = b.groupid
                    ", null);

                    return data;
                }
            });

        }

        public override PageResult Index(BeeDataAdapter dataAdapter)
        {
            DataTable result = null;
            using (DbSession dbSession = GetDbSession())
            {
                result = dbSession.Query("AuthGroup", SqlCriteria.New.Equal("grouptype", 2).Equal("delflag", 0)); // 组织用户组

                ViewData.Add("roleinfo", dbSession.Query("AuthRole", SqlCriteria.New.Equal("delflag", false)));
            }

            return View(result);
        }

        public void OrgSave(BeeDataAdapter dataAdapter)
        {
            AuthGroup authGroup = ConvertUtil.ConvertDataToObject<AuthGroup>(dataAdapter);
            string roleInfo = dataAdapter.TryGetValue<string>("roleinfo", string.Empty);

            authGroup.GroupType = 2; // 1 为正常用户组， 2：为组织用户组

            Save(authGroup, roleInfo);

            using (DbSession dbSession = GetDbSession())
            {
                dataAdapter.RemoveKey("id");
                string orgCode = StringUtil.GetCapital(authGroup.Name);
                dataAdapter.Add("orgcode", orgCode);
                bool existFlag = dbSession.IsExist("Organization", SqlCriteria.New.Equal("groupid", authGroup.Id));
                if (existFlag)
                {
                    dbSession.Update("Organization", dataAdapter, SqlCriteria.New.Equal("groupid", authGroup.Id));
                }
                else
                {
                    dataAdapter["groupid"] = authGroup.Id;
                    dbSession.Insert("Organization", dataAdapter);
                }
            }

            DataMapping.Instance.Refresh("OrganizationMapping");
        }

        public override BeeDataAdapter Detail(int id)
        {
            BeeDataAdapter dataAdapter = base.Detail(id);

            using (DbSession dbSession = GetDbSession())
            {
                Organization orgnization = dbSession.Query<Organization>(SqlCriteria.New.Equal("groupid", id)).FirstOrDefault();

                dataAdapter.Merge(BeeDataAdapter.From(orgnization), false);

                Employee employee = dbSession.Query<Employee>(SqlCriteria.New.Equal("id", orgnization.OwnerEmployeeId)).FirstOrDefault();
                if (employee != null)
                {
                    dataAdapter["TrueName"] = employee.TrueName;
                }
            }

            return dataAdapter;
        }

        public DataTable Suggest(BeeDataAdapter dataAdapter)
        {
            string name = dataAdapter.TryGetValue<string>("name", string.Empty);

            SqlCriteria sqlCriteria = SqlCriteria.New;
            sqlCriteria.Equal("delflag", false);


            if (!string.IsNullOrEmpty(name))
            {
                sqlCriteria.StartWith("orgcode", name)
                    .Or(SqlCriteria.New.StartWith("name", name));
            }

            int groupType = dataAdapter.TryGetValue<int>("ct", 0);
            if (groupType > 0)
            {
                sqlCriteria.Equal("grouptype", groupType);
            }

            DataTable data = DataMapping.Instance.GetMapping("OrganizationMapping") as DataTable;

            int recordCount = 0;
            // 最多推荐5条
            data = DataUtil.Query(data, sqlCriteria, "id asc", 1, 5, ref recordCount);

            return data;
        }

        public PageResult Lookup(BeeDataAdapter dataAdapter)
        {
            SqlCriteria sqlCriteria = SqlCriteria.New;
            sqlCriteria.Equal("delflag", false);

            int groupType = dataAdapter.TryGetValue<int>("ct", 0);
            if (groupType > 0)
            {
                sqlCriteria.Equal("grouptype", groupType);
            }

            DataTable data = DataMapping.Instance.GetMapping("OrganizationMapping") as DataTable;

            data = DataUtil.Query(data, sqlCriteria);

            return View(data);
        }

        public PageResult EmployeeOrgLookup(BeeDataAdapter dataAdapter)
        {
            DataTable employeeOrgData = EmployeeInfoManager.Instance.EmployeeOrgLookup();

            return View(employeeOrgData);
        }
    }

}
